<template>
  <div id="Content-page">
    <div class="content-main">
      <div class="category-button">
        <el-button @click="dialogTableVisible = true">+新建分类</el-button>
        <el-button id="new-button" @click="addProduct">新建商品</el-button>
      </div>
      <el-tabs v-model="tabName" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane
          v-for="item in filterTabData"
          :key="item._id"
          :label="item.label"
          :name="item.type"
        ></el-tab-pane>
      </el-tabs>
      <!-- 商品展示 -->
      <div class="product-management">
        <div class="category-name">
          <div class="category-active" v-for="(item, index) in categoryList" :key="index"
          @click="selectCategory(index, item._id)"
          :class="{ categoryActive: index === selectIndex }">
            <el-image
              :src="item.icon"
              fit="contain"
              style="width: 30px; height: 30px"
            ></el-image>
            <span>{{ item.categoryName }}({{ item.quantity }})</span>
          </div>
        </div>
        <!-- 右边商品 -->
        <div class="product-list-data">
          <div class="product-item" v-for="(item, index) in productDataList" :key="index">
            <div>
              <el-image
                :src="item.goods_image"
                fit="cover"
                style="width: 100px; height: 80px"
              ></el-image>
            </div>
            <div class="product-features">
              <div>{{ item.goods_name }}</div>
              <div>
                ¥{{ item.display_price }}&nbsp;&nbsp;&nbsp;库存：{{
                  item.total_stock
                }}&nbsp;&nbsp;&nbsp;属性：{{
                  item.goods_stats.map((item_a) => item_a.productAttributes).join("，")
                }}
              </div>
              <div>销售:{{ item.sales_volume }}</div>
            </div>
            <div class="product-actions">
              <el-button
                :type="item.delist ? 'success' : 'info'"
                size="default"
                @click="offlineProduct(index, item.goods_name, item._id, item.delist)"
              >
                {{ item.delist ? "上架" : "下架" }}
              </el-button>
              <div>
                <el-text
                  type="success"
                  @click="deleteProduct(index, item.goods_name, item._id, item.category_id)"
                  >删除
                  </el-text>
                <el-text type="success" @click="editProduct(item)">编辑</el-text>
              </div>
            </div>
          </div>
          <!-- 没有数据的提示 -->
        <el-text type="info" class="no-data" v-if="productDataList.length <= 0"
            >没有商品数据</el-text
          >
      <!-- 分页 -->
          <el-pagination
            class="pager-next"
            background
            layout="prev, pager, next"
            :total="totalQuantity"
            hide-on-single-page
            :current-page="page"
            @current-change="currentChange"
          />
    </div>
        </div>
        <!-- 新建分类 -->
         <el-dialog
        v-model="dialogTableVisible"
        title="新建分类"
        width="400"
        :close-on-click-modal="false"
      >
        <span class="upload-span">填写分类名</span>
        <el-input v-model="categoryName" placeholder="请输入分类名" clearable></el-input>
        <span class="upload-span">上传分类图标</span>
        <elUpload @uploadedUrl="onLoadUrl"></elUpload>
        <div class="submit-category">
          <el-button id="new-button" @click="submitCategory" :loading="categoryLoading"
            >提交</el-button
          >
        </div>
      </el-dialog>
      </div>  
      
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getFilterProductsApi, getCategoryApi, getGoodsApi,offlineProductsApi,onlineProductsApi,deleteProductsApi ,uploadCategoryApi} from "@/api/api";
import type { getGoodsRes, filterProductsType, getCategoryType } from "@/types";
import { ElMessageBox } from "element-plus";
import { editSpecificProduct } from "@/store/index";
import { useRouter } from 'vue-router';
import { nullCheck } from "@/api/form-check";
import elUpload from '@/components/el-upload.vue';
const $router = useRouter()
onMounted(async () => {
  const filterTab = await getFilterProductsApi();
  const productCategory = await getCategoryApi();
  filterTabData.value = filterTab.data;
  categoryList.value = productCategory.data;
  tabName.value = filterTab.data[0].type;
  categoryid.value = productCategory.data[0]._id
  //进入页面，默认第一个tab和第一个分类
  await getGoods(filterTab.data[0].type, productCategory.data[0]._id, 1);
});
//存储tab
const filterTabData = ref<filterProductsType[]>([]);
//存储商品分类
const categoryList = ref<getCategoryType[]>([]);
//点击商品分类的下表
const selectIndex = ref(0)
//存储商品分类id
const categoryid = ref('')
// 选择商品分类筛选商品数据
async function selectCategory(index: number, _id: string) {
  selectIndex.value = index;
  categoryid.value = _id;
  page.value = 1;
  await getGoods(tabName.value, categoryid.value, page.value);
}
//筛选结果
async function getGoods(filterval: string, categoryid: string, page: string | number) {
  const res = await getGoodsApi({ filterval, categoryid, page });
  productDataList.value = res.data.res;
  totalQuantity.value = res.data.total;
}
//存储商品列表数据
const productDataList = ref<getGoodsRes[]>([]);
//存储数据总条数
const totalQuantity = ref(0);

const tabName = ref("");
// tab切换时触发
async function handleClick(tab: string) {
  tabName.value = tab;
  page.value = 1;
  await getGoods(tabName.value, categoryid.value, page.value);
}
const page = ref(1)
//切换页数触发
async function currentChange(value:number){
    page.value = value
    await getGoods(tabName.value, categoryid.value, page.value);
}
// 下架或者上架商品
function offlineProduct(index: number, name: string, id: string, delist: boolean) {
  ElMessageBox.confirm(`确定${delist ? "上架" : "下架"}${name}这个商品吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async (res) => {
    if (delist) {
      // 上架
      await onlineProductsApi({ goodsid: id });
      productDataList.value[index].delist = false;
    } else {
      // 下架
      await offlineProductsApi({ goodsid: id });
      productDataList.value[index].delist = true;
    }
  });
}
function deleteProduct(index: number, name: string, id: string, category_id: string) {
  ElMessageBox.confirm(`确定删除${name}这个商品吗？删除后将不可找回`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async (res) => {
    await deleteProductsApi({ goodsid: id });
    productDataList.value.splice(index, 1);
    const categoryIndex = categoryList.value.findIndex((item) => item._id === category_id);
    categoryList.value[categoryIndex].quantity--;
  });
}

function editProduct(data:getGoodsRes){
    const { _id, category_id, goods_image, goods_name, goods_describe, goods_stats, hasSpecs } = data;
    editSpecificProduct().$patch((val) => {
    val.data = {
      goods_id: _id,
      category_id: category_id,
      goods_image: goods_image,
      goods_name: goods_name,
      goods_describe: goods_describe,
      goods_stats: goods_stats,
      hasSpecs: hasSpecs,
    };
    val.type = "002";
  });
  $router.push("/add-product");
}
// 新增商品
function addProduct() {
  editSpecificProduct().$patch((val) => {
    val.type = "001";
  });
  $router.push("/add-product");
}
// 显示或者隐藏分类弹窗
const dialogTableVisible = ref(false);
const categoryName = ref("");
// 存储上传的分类图标
const iconUrl = ref("");
// 接收子组件上传的图标
function onLoadUrl(url: string) {
  iconUrl.value = url;
}
// 存储提交按钮状态
const categoryLoading = ref(false);
async function submitCategory() {
  nullCheck(categoryName.value, "请输入分类名");
  nullCheck(iconUrl.value, "请上传分类图标");
  categoryLoading.value = true;
  try {
    await uploadCategoryApi({ categoryName: categoryName.value, icon: iconUrl.value });
    categoryLoading.value = false;
    dialogTableVisible.value = false;
    categoryName.value = "";
    iconUrl.value = "";
  } catch (error) {
    categoryLoading.value = false;
  }
}
</script>

<style scoped>
.category-button {
  display: flex;
  justify-content: end;
}
.product-management {
  display: flex;
}
.category-name {
  width: 180px;
  height: 600px;
  overflow-y: auto;
}
.category-active {
  display: flex;
  align-items: center;
  padding: 20px 10px;
  cursor: pointer;
}
.category-active span {
  padding-left: 10px;
}
.product-list-data {
  flex: 1;
}
.product-item {
  display: flex;
  padding: 0 20px 20px 20px;
}
.product-features {
  flex: 1;
  padding: 0 15px;
}
.product-features div:nth-child(1) {
  font-weight: bold;
}
.product-features div:nth-child(2) {
  padding: 10px 0;
}
.product-features div:nth-child(3) {
  color: #cacbd4;
}
.product-actions {
  display: flex;
  flex-direction: column;
  height: 80px;
  justify-content: space-between;
}
.product-actions span {
  margin: 0 5px;
  cursor: pointer;
}
.product-actions div {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.categoryActive {
  background-color: #f0f2f5;
}
.upload-span {
  display: block;
  margin: 10px 0;
}
.submit-category {
  display: flex;
  justify-content: center;
  padding-top: 25px;
}
.submit-category >>> .el-button--success {
  width: 40%;
}
.no-data {
  display: flex;
  justify-content: center;
  padding-top: 100px;
}
</style>
